<script lang="ts" setup>
import type { CSSProperties } from 'vue'
import { computed } from 'vue'
import { Badge, Image } from 'ant-design-vue'
import { useDesign } from '@/hooks/web/useDesign'
import { propTypes } from '@/utils/propTypes'

defineOptions({ name: 'TableImage' })

const props = defineProps({
  imgList: propTypes.arrayOf(propTypes.string),
  size: propTypes.number.def(40),
  // 是否简单显示（只显示第一张图片）
  simpleShow: propTypes.bool,
  // 简单模式下是否显示图片数量的badge
  showBadge: propTypes.bool.def(true),
  // 图片间距
  margin: propTypes.number.def(4),
  // src前缀，将会附加在imgList中每一项之前
  srcPrefix: propTypes.string.def(''),
  // fallback,加载失败显示图像占位符。
  fallback: propTypes.string.def(
    '',
  ),
})

const PreviewGroup = Image.PreviewGroup

const getWrapStyle = computed((): CSSProperties => {
  const { size } = props
  const s = `${size}px`
  return { height: s, width: s }
})

const { prefixCls } = useDesign('basic-table-img')
</script>

<template>
  <div
    v-if="imgList && imgList.length"
    :class="prefixCls"
    class="mx-auto flex items-center"
    :style="getWrapStyle"
  >
    <Badge v-if="simpleShow" :count="!showBadge || imgList.length === 1 ? 0 : imgList.length">
      <div class="img-div">
        <PreviewGroup>
          <template v-for="(img, index) in imgList" :key="img">
            <Image
              :width="size"
              :style="{
                display: index === 0 ? '' : 'none !important',
              }"
              :src="srcPrefix + img"
              :fallback="fallback"
            />
          </template>
        </PreviewGroup>
      </div>
    </Badge>
    <PreviewGroup v-else>
      <template v-for="(img, index) in imgList" :key="img">
        <Image
          :width="size"
          :style="{ marginLeft: index === 0 ? 0 : `${margin}px` }"
          :src="srcPrefix + img"
          :fallback="fallback"
        />
      </template>
    </PreviewGroup>
  </div>
</template>

<style lang="less">
@prefix-cls: ~'@{namespace}-basic-table-img';

.@{prefix-cls} {
  .ant-image {
    margin-right: 4px;
    cursor: zoom-in;

    img {
      border-radius: 2px;
    }
  }

  .img-div {
    display: inline-grid;

    > .ant-image:nth-of-type(n + 2) {
        display: none;
      }
  }
}
</style>
